<!--
 * @Author: LiYuan
 * @Date: 2021-10-09 10:17:20
 * @LastEditTime: 2021-10-28 22:59:31
 * @LastEditors: LiYuan
 * @Description: 新建or编辑服务报告
 * You build it, You run it.
-->
<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal='false'>
    <div class="service-report-edit-content">
      <el-form label-position="top" ref="form" :model='form' :rules="rules">
        <el-form-item :label="$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle31')" prop="taskStatus">
          <el-select v-model="form.taskStatus" :disabled='form.taskStatus === "finished"'>
            <el-option 
              v-for="item in taskStatusOptions"
              :disabled="formatTaskTypeDisabled(item.optionName)"
              :key="item.optionName"
              :label="getStateName(item)"
              :value="item.optionName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle32')" prop="templateType">
          <el-radio-group v-model="form.templateType">
            <el-radio :label="1">
              <span class="mar-r-12">{{$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle33')}}</span>
              <el-button
                :disabled="form.templateType === 2"
                :type="form.templateType === 1 ? 'primary': 'default'" 
                plain 
                size="small"
                @click="openTemplateDialog('system')">
                {{$t('common.base.setting')}}
              </el-button>
            </el-radio>
            <el-radio :label="2">
              <span class="mar-r-12">{{$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle34')}}</span>
              <el-button
                :disabled="form.templateType === 1"
                :type="form.templateType === 2 ? 'primary': 'default'" 
                plain
                @click="openTemplateDialog('personal')"
                size="small">
                {{$t('common.base.setting')}}
              </el-button>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="needSign">
          <template slot="label">
            {{$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle35')}}
            <el-tooltip
              placement="top"
              :content="$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle36')">
              <i class="el-icon-question el-tooltip"></i>
            </el-tooltip>
          </template>
          <el-select v-model="form.needSign">
            <el-option 
              v-for="item in signOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <div v-if="form.templateType === 2 && form.needSign" class="needSign-text">{{ $t('task.setting.taskTypeSetting.flow.components.serviceReportTitle40') }}</div>
        </el-form-item>
        
        <el-form-item prop="foreignName">
          <template slot="label">
            {{$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle37')}}
            <el-tooltip
              placement="top"
              :content="$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle38')">
              <i class="el-icon-question el-tooltip"></i>
            </el-tooltip>
          </template>
          <div class="foreign-name">
            <el-input v-model="form.foreignName" :maxlength="maxlength" :placeholder="$t('task.setting.taskTypeSetting.flow.components.serviceReportTitle39')"></el-input>
            <el-button type="primary" class="mar-l-10" @click="openVariableDialog()">{{ $t('task.setting.taskTypeSetting.flow.components.addVariable') }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button @click="dialogVisible=false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" :disabled="pending" :loading="pending" @click="handleSave">{{$t('common.base.makeSure')}}</el-button>
    </div>
    <el-dialog
      :title="$t('task.setting.taskTypeSetting.flow.components.addVariable')"
      :visible.sync="variableDialogVisible"
      append-to-body
    >
      <div class="add-variable-dialog-content">
        <el-form label-position="top" :model="variableForm">
          <el-form-item :label="$t('task.setting.taskTypeSetting.flow.components.taskFields')" prop="selectField">
            <el-select v-model="variableForm.selectField">
              <el-option 
                v-for="item in allFields"
                :key="item.fieldName"
                :label="item.displayName"
                :value="item.fieldName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="variableDialogVisible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" :disabled="pending" :loading="pending" @click="handleAddVariable">{{$t('task.setting.taskTypeSetting.flow.components.insert')}}</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import _ from 'lodash';
import * as SettingTaskApi from '@src/api/SettingTaskApi.js';
import { getTaskServiceReportNameField } from '@src/api/TaskApi.ts';
import i18n from '@src/locales'
import TaskStateEnum from '@model/enum/TaskStateEnum'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

export default {
  name: 'service-report-edit-dialog',
  props: {
    'taskStatusOptions': {
      type: Array,
      default: () => []
    },
    'taskTypeId': {
      type: String,
      default: ''
    },
    'existTypeStatus': {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      maxlength: 120,
      internationalGray,
      serviceReportDetail: {},
      dialogVisible: false,
      pending: false,
      type: 'create',
      form: {
        taskStatus: '',
        templateType: 1,
        needSign: 0,
        foreignName: '',
        setting: null
      },
      rules: {
        taskStatus: [{ required: true, message: i18n.t('task.setting.taskTypeSetting.flow.components.serviceReportTip1'), trigger: 'change' }],
        templateType: [{ required: true, message: i18n.t('task.setting.taskTypeSetting.flow.components.serviceReportTip2'), trigger: 'change' }],
        needSign: [{ required: true, message: i18n.t('task.setting.taskTypeSetting.flow.components.serviceReportTip3'), trigger: 'change' }]
      },
      signOptions: [
        {
          value: 0,
          label: i18n.t('common.base.notNeed')
        },
        {
          value: 1,
          label: i18n.t('common.base.need')
        },
      ],
      variableDialogVisible: false,
      variableForm: {
        selectField: '',
      },
      allFields: [],
    }
  },
  computed: {
    title() {
      return this.type === 'create' ? i18n.t('common.base.createRuler') : i18n.t('common.base.editRule')
    }
  },
  mounted() {
    this.getTaskFields()
  },
  methods: {
    // 获取工单状态的多语言名称
    getStateName(val) {
      const { optionName: value, displayName } = val
      // 自定义节点处理
      const name = TaskStateEnum.getName(value)
      return name ? name : displayName
    },
    formatTaskTypeDisabled(taskType) {
      return this.existTypeStatus.indexOf(taskType) < 0 ? false : true
    },
    async getServiceReportDetail(id) {
      const { success, data } = await SettingTaskApi.getServiceReportTemplate({id})
      this.serviceReportDetail = success ? data : {}


      this.form = _.cloneDeep(this.serviceReportDetail)

      console.log(this.form, 'getServiceReportTemplate')
    },

    async openDialog(type, item) {
      this.dialogVisible = true
      // 初始化一下
      this.type = type
      if(type === 'edit') {
        await this.getServiceReportDetail(item.id)
      } else {
        if(this.$refs.form) {
          this.form = {
            taskStatus: '',
            templateType: 1,
            needSign: 0,
            foreignName: '',
            setting: null
          }
          this.$refs.form.resetFields()
        }
      }
    },

    openTemplateDialog(type) {

      console.log(this.form?.setting, 'this.form?.settingthis.form?.setting')
      this.$emit('openTemplateDialog', type, this.form?.setting || {})
    },

    updateSetting(setting, params) {
      this.$set(this.form, 'setting', setting)
      this.$set(this.form.setting, 'templates_en', params.templates_en)
      this.$set(this.form.setting, 'templates_ru', params.templates_ru)
    },
    
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(!this.form.setting) {
            return this.$message.warning(i18n.t('task.setting.taskTypeSetting.flow.components.serviceReportTip4'))
          } else {
            if(this.form.templateType === 1 && !this.form.setting?.tenantFields) { // 系统模版
              return this.$message.warning(i18n.t('task.setting.taskTypeSetting.flow.components.serviceReportTip5'))
            } else if(
              this.form.templateType === 2 && this.internationalGray &&
              (!this.form.setting?.templates || this.form.setting?.templates.length <= 0) && 
              (!this.form.setting?.templates_en || this.form.setting?.templates_en?.length <= 0) && 
              (!this.form.setting?.templates_ru || this.form.setting?.templates_ru?.length <= 0)
            ) { // 国际化临时处理
              return this.$message.warning(i18n.t('task.setting.taskTypeSetting.flow.components.serviceReportTip6'))
            } else if(this.form.templateType === 2 && !this.internationalGray && (!this.form.setting?.templates || this.form.setting?.templates.length <= 0)) { // 个人模版
              return this.$message.warning(i18n.t('task.setting.taskTypeSetting.flow.components.serviceReportTip6'))
            }
          }
          const params = {...this.form, taskTypeId: this.taskTypeId}
          this.pending = true
          const FetchFun = this.type === 'create' ? SettingTaskApi.createServiceReportTemplate : SettingTaskApi.editServiceReportTemplate
            FetchFun(params).then(res => {
              if(res.success) {
                this.$emit('success')
                this.dialogVisible = false
              } else {
                this.$message.error(res.message)
              }
              this.pending = false
            })
            .catch(err => { console.error(err)})
        } else {
          return false;
        }
      });
    },
    async getTaskFields() {
      try {
        const res = await getTaskServiceReportNameField({templateId: this.taskTypeId})
        this.allFields = res.result || []
      } catch(error) {
        console.error('getTaskServiceReportNameField catch error', error)
      }
    },
    openVariableDialog() {
      this.variableForm.selectField = ''
      this.variableDialogVisible = true
    },
    handleAddVariable() {
      if(!this.variableForm.selectField) return this.$message.warning(i18n.t('common.wiki.selectFieldValidate'));
      
      let content = this.form.foreignName;
      if (content && content.indexOf(this.variableForm.selectField) > -1) return this.$message.warning(i18n.t('common.wiki.insertFieldValidate'));
      const name = `${content || i18n.t("task.serviceReport")} {{${this.variableForm.selectField}}}`
      if (name.length > this.maxlength) return this.$platform.alert(i18n.t('common.validate.nameLimit', {limit: this.maxlength}))
      this.form.foreignName = name
      this.variableDialogVisible = false
    },
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content div {
  width: 100%;
}
.el-button.is-plain:hover {
  border-color: #ebeef5 !important;
  color: #c0c4cc !important;
}

.needSign-text {
  color: #9fa0a2 !important;
  font-size: 12px;
}

.foreign-name {
  display: flex;
}
</style>